﻿using System;
using System.Text;
using PostRequestFactory.Core.Utilities;
using PostRequestFactory.Core.Interfaces;

namespace PostRequestFactory.Core.Parameters
{
    /// <summary>
    /// This class is used for providing content
    /// for a post request which will use 'application/x-www-form-urlencoded' form
    /// content type. Content will be encoded by using Microsoft's url encode mechanism
    /// </summary>
    public class BasicRequestParameter : IRequestParameter
    {
        public string Name { get; private set; }

        public string ContentType { get { return "application/x-www-form-urlencoded"; } }

        public string ContentDisposition { get { return "form-data"; } }

        public string Content { get; private set; }

        public RequestParameterType ParameterType
        {
            get { return RequestParameterType.Basic; }
        }

        #region Ctors
        
        /// <summary>
        /// Creates a new instance of a BasicRequestParameter.
        /// </summary>
        /// <param name="name">Control name</param>
        /// <param name="content">Control content/value</param>
        /// <param name="currentContentEncoding">Encoding used by the current content</param>
        public BasicRequestParameter(string name, string content, Encoding currentContentEncoding)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("'name' parameter cannot be null or empty", "name");
            }

            //set default UTF8 encoding
            if (currentContentEncoding == null)
            {
                currentContentEncoding = Encoding.UTF8;
            }

            Name = name;

            /*
             * Content is UrlEncoded by using the following rules:
             * Control names and values are escaped. Space characters are replaced by `+', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by `%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., `%0D%0A').
             * The control names/values are listed in the order they appear in the document. The name is separated from the value by `=' and name/value pairs are separated from each other by `&'.
             */
            Content = EncoderUtility.UrlEncode(content, currentContentEncoding);
        }

        /// <summary>
        /// Creates a new instance of a BasicRequestParameter.
        /// UTF8 will be used as content encoding.
        /// </summary>
        /// <param name="name">Control name</param>
        /// <param name="content">Control content/value</param>
        public BasicRequestParameter(string name, string content)
            : this(name, content, Encoding.UTF8)
        {
        } 

        #endregion
    }
}
